import { getUserInfo, logout, getTips } from '@/api/user'
import { getToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    userId: '',
    username: '',
    buildingName: '',
    phone: '',
    alarmNum: '',
    notifyNum: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_BUILDINGNAME: (state, buildingName) => {
      state.buildingName = buildingName
    },
    SET_PHONE: (state, phone) => {
      state.phone = phone
    },
    SET_ALARMNUM: (state, alarmNum) => {
      state.alarmNum = alarmNum
    },
    SET_NOTIFYNUM: (state, notifyNum) => {
      state.notifyNum = notifyNum
    }
  },

  actions: {
    // dispatch 获取用户信息
    GetUserInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          commit('SET_USERID', response.userId)
          commit('SET_USERNAME', response.username)
          commit('SET_BUILDINGNAME', response.buildingName)
          commit('SET_PHONE', response.phone)
          sessionStorage.setItem('username', response.userName)

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // dispatch 获取告警和消息数量
    GetTips ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getTips().then(response => {
          commit('SET_ALARMNUM', response.alarmCount)
          commit('SET_NOTIFYNUM', response.notifyCount)

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // dispatch 点击退出
    Logout ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          removeToken()
          console.log('token')
          // commit('SET_TOKEN', '')
          // commit('SET_USERID', '')
          // commit('SET_NAME', '')
          // commit('SET_BUILDINGNAME', '')
          // commit('SET_PHONE', '')

          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // dispatch 非正常退出
    FedLogout ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
